package com.example.pda.net;

import android.text.TextUtils;

import com.example.pda.data.Result;

import androidx.annotation.NonNull;

/**
 * A generic class that holds a result success w/ data or an error exception.
 */
public class CallResult<T> {

    public T data;

    private String code; // 0001=成功，0000=失败

    private String msg;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean isSuccess() {
        return !TextUtils.isEmpty(this.code) && TextUtils.equals(code, "0001");
    }

    public boolean isErrorResult(){
        return TextUtils.isEmpty(this.code) || !isSuccess();
    }

    @NonNull
    @Override
    public String toString() {
        if (this instanceof CallResult.Success) {
            Success<T> success = (Success<T>) this;
            return "Success[data=" + success.getData().toString() + "]";
        } else if (this instanceof CallResult.Error) {
            Error<T> error = (Error<T>) this;
            return "Error[exception=" + error.getError().toString() + "]";
        }
        return "";
    }

    // Success sub-class
    public final static class Success<T> extends CallResult<T> {

        public Success(T data) {
            this.data = data;
            setCode("0001");
        }
    }

    // Error sub-class
    public final static class Error<T> extends CallResult<T> {
        private final Exception error;

        public Error(Exception error) {
            this.error = error;
            setMsg(error.getMessage());
        }

        public Exception getError() {
            return this.error;
        }
    }
}